import store from '@/store/index'
/**
 * 递归匹配
 * @param {*} fun 回调校验是否匹配
 * @param {*} list 后台返回的permission多级数组
 */
export const findMatchPermissionItem = (fun = () => true, list) => {
  
  if (!fun || !list || list.length === 0) {
    return null
  }
 
  for (const v of list) {
    if (fun(v)) {
      // 找到了
      
      return v
    }
    if (v.children) {
      const res = findMatchPermissionItem(fun, v.children)
      if (res) {
        return res
      }
    }
  }
  return null
}
/**
 * 递归匹配到二级菜单是否有权限
 * @param {*} href 二级菜单路由
 * @param {*} list 后台返回的permission多级数组
 */
export const findGrantedMenuItem = (menuId, list) => {

  return findMatchPermissionItem(
    item => menuId && item.id && item.id === menuId,
    list
  )
}
/**
 * 处理成为有权限的路由
 * @param {*} cloneMenuList
 * @param {*} permissionList
 */
export const processGrantedMenu = (cloneMenuList, permissionList) => {
  if (
    !cloneMenuList ||
    cloneMenuList.length === 0 ||
    !permissionList ||
    permissionList.length === 0
  ) {
    return
  }
  for (let i = 0; i < cloneMenuList.length; i++) {
    if (cloneMenuList[i].path !== '/') {
      //在权限配置中寻找，路由是否有权限
      const res = findGrantedMenuItem(cloneMenuList[i].menuId, permissionList)
    
      if (!res) {
        // 未找到
        cloneMenuList.splice(i--, 1)
      } else if(cloneMenuList[i].child) {
        // 递归
        processGrantedMenu(cloneMenuList[i].child, permissionList)
      }
    } 
    // else if (cloneMenuList[i].child) {
    //   // 递归
    //   processGrantedMenu(cloneMenuList[i].child, permissionList)
    // }
  }
}
/**
 * 通过id判断该功能是否有权限
 * @param {*} id 二级菜单路由
 */
export const checkGranted = id => {
  return findMatchPermissionItem(
    item => Number(item.id) === Number(id) && item.is_bind,
    store.getters.permissionData
  )
}
